//
//  TFSinglePhotoPickerHelper.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/12/16.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFSinglePhotoPickerHelper.h"
#import <objc/runtime.h>
#import "TFPhotoPickerHelper.h"
#import "TFPhotoResourceHelper.h"
#import "TFPhotoCropViewController.h"

@interface UIImagePickerController (PickerHelper)

@property (nonatomic, strong) TFSinglePhotoPickerHelper *pickerHelper;

@end

@implementation UIImagePickerController (PickerHelper)

- (void)setPickerHelper:(TFSinglePhotoPickerHelper *)pickerHelper {
    objc_setAssociatedObject(self, @selector(pickerHelper), pickerHelper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (TFSinglePhotoPickerHelper *)pickerHelper {
    return objc_getAssociatedObject(self, @selector(pickerHelper));
}

@end

@interface TFSinglePhotoPickerHelper ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,TFPhotoCropViewControllerDelegate>

@property (nonatomic, weak) id<TFSinglePhotoPickerHelperDelegate> delegate;

@property (nonatomic, strong) TFPhotoCropInfoModel *cropInfoModel;

@end


@implementation TFSinglePhotoPickerHelper

+ (void)showSystemSinglePhotoPickerActionSheetInViewController:(UIViewController *)viewController withTitle:(NSString *)title infos:(NSArray<TFSinglePhotoPickerActionSheetInfoModel *> *)infos mediaTypes:(NSArray<NSString *> *)mediaTypes allowsEditing:(BOOL)allowsEditing delegate:(id<TFSinglePhotoPickerHelperDelegate>)delegate{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if (!infos) {
        TFSinglePhotoPickerActionSheetInfoModel *cameraTypeModel = [[TFSinglePhotoPickerActionSheetInfoModel alloc] init];
        cameraTypeModel.info = [TFPhotoResourceHelper localizedStringWithKey:@"拍照"];
        cameraTypeModel.sourceType = UIImagePickerControllerSourceTypeCamera;
        TFSinglePhotoPickerActionSheetInfoModel *photoLibraryTypeModel = [[TFSinglePhotoPickerActionSheetInfoModel alloc] init];
        photoLibraryTypeModel.info = [TFPhotoResourceHelper localizedStringWithKey:@"从手机相册选择"];
        photoLibraryTypeModel.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        infos = @[cameraTypeModel,photoLibraryTypeModel];
    }
    for (TFSinglePhotoPickerActionSheetInfoModel *info in infos) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:info.info style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [TFSinglePhotoPickerHelper showSystemSinglePhotoPickerInViewController:viewController withSourceType:info.sourceType mediaTypes:mediaTypes allowsEditing:allowsEditing delegate:delegate];
        }];
        [alertVC addAction:action];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"取消"] style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:cancelAction];
    [viewController presentViewController:alertVC animated:YES completion:nil];
}

+ (void)showSystemSinglePhotoPickerInViewController:(UIViewController *)viewController withSourceType:(UIImagePickerControllerSourceType)sourceType mediaTypes:(NSArray<NSString *> *)mediaTypes allowsEditing:(BOOL)allowsEditing delegate:(id<TFSinglePhotoPickerHelperDelegate>)delegate{
    TFSinglePhotoPickerHelper *pickerHelper = [[TFSinglePhotoPickerHelper alloc] init];
    pickerHelper.delegate = delegate;
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
    pickerVC.delegate = pickerHelper;
    pickerVC.pickerHelper = pickerHelper;
    pickerHelper.cropInfoModel = nil;
    pickerHelper.imagePickerViewController = pickerVC;
    if ([pickerHelper.delegate respondsToSelector:@selector(singlePhotoPickerHelper:pickerCustomCropInfoModel:)]) {
        allowsEditing = NO;
        pickerHelper.cropInfoModel = [pickerHelper.delegate singlePhotoPickerHelper:pickerHelper pickerCustomCropInfoModel:pickerVC];
    }
    pickerVC.allowsEditing = allowsEditing;
    if (mediaTypes) {
        pickerVC.mediaTypes = mediaTypes;
    }
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        NSString *message = @"";
        switch (sourceType) {
            case UIImagePickerControllerSourceTypeCamera:
            {
                message = [TFPhotoResourceHelper localizedStringWithKey:@"抱歉，您的手机还没有相机"];
            }
                break;
            case UIImagePickerControllerSourceTypePhotoLibrary: {
                message = [TFPhotoResourceHelper localizedStringWithKey:@"抱歉，您的手机不支持打开系统相册"];
            }
            default:
                break;
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"提示"] message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:[TFPhotoResourceHelper localizedStringWithKey:@"确定"] style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [viewController presentViewController:alert animated:YES completion:nil];
    }
    else {
        pickerVC.sourceType = sourceType;
    }
    if ([pickerHelper.delegate respondsToSelector:@selector(singlePhotoPickerHelper:willPresentPicker:)]) {
        [pickerHelper.delegate singlePhotoPickerHelper:pickerHelper willPresentPicker:pickerVC];
    }
    [viewController presentViewController:pickerVC animated:YES completion:nil];
}

#pragma mark - help actions.

+ (UIImage *)getOriginalImageWithInfo:(NSDictionary<NSString *,id> *)info {
    return [info objectForKey:UIImagePickerControllerOriginalImage];
}

+ (PHAsset *)getOriginalImageAssetWithInfo:(NSDictionary<NSString *,id> *)info {
    NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
    if (url) {
        PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
        return result.firstObject;
    }
    return nil;
}

+ (UIImage *)getEditedImageWithInfo:(NSDictionary<NSString *,id> *)info {
    return [info objectForKey:UIImagePickerControllerEditedImage];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:pickerDidCancel:)]) {
        [self.delegate singlePhotoPickerHelper:self pickerDidCancel:picker];
    }
    else {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if (self.cropInfoModel) {
        TFPhotoCropViewController *cropVC = [[TFPhotoCropViewController alloc] init];
        cropVC.delegate = self;
        cropVC.image = [TFSinglePhotoPickerHelper getOriginalImageWithInfo:info];
        [picker presentViewController:cropVC animated:YES completion:nil];
    }
    else {
        if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:picker:didFinishPickingMediaWithInfo:)]) {
            [self.delegate singlePhotoPickerHelper:self picker:picker didFinishPickingMediaWithInfo:info];
        }
        else {
            [picker dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

#pragma mark - UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:picker:willShowViewController:)]) {
        [self.delegate singlePhotoPickerHelper:self picker:(UIImagePickerController *)navigationController willShowViewController:viewController];
    }
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:picker:didShowViewController:)]) {
        [self.delegate singlePhotoPickerHelper:self picker:(UIImagePickerController *)navigationController didShowViewController:viewController];
    }
}

#pragma mark - TFPhotoCropViewControllerDelegate

- (TFPhotoCropInfoModel *)photoCropViewControllerCropInfoModel:(TFPhotoCropViewController *)photoCropViewController {
    return self.cropInfoModel;
}

- (void)photoCropViewControllerDidCancel:(TFPhotoCropViewController *)photoCropViewController {
    UIImagePickerController *picker = (UIImagePickerController *)photoCropViewController.presentingViewController;
    if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:pickerDidCancel:)]) {
            [self.delegate singlePhotoPickerHelper:self pickerDidCancel:(UIImagePickerController *)picker.presentingViewController];
        }
        else {
            [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
    }
    else {
        [photoCropViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)photoCropViewControllerDidFinish:(TFPhotoCropViewController *)photoCropViewController {
    UIImagePickerController *picker = (UIImagePickerController *)photoCropViewController.presentingViewController;
    if ([self.delegate respondsToSelector:@selector(singlePhotoPickerHelper:picker:didFinishPickingMediaWithInfo:)]) {
        [self.delegate singlePhotoPickerHelper:self picker:(UIImagePickerController *)picker.presentingViewController didFinishPickingMediaWithInfo:@{UIImagePickerControllerEditedImage:photoCropViewController.cropedImage,UIImagePickerControllerOriginalImage:photoCropViewController.image}];
    }
    else {
        [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)dealloc {
    NSLog(@"\n******************************************\n %s---line:%d \n******************************************",__func__,__LINE__);
} 

@end
